package com.badger.generator.pattern;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import com.badger.generator.constant.DataBaseDriver;
import com.badger.generator.entity.GeneratorAttr;
import com.badger.generator.enums.DataBaseFieldEnum;
import com.badger.generator.enums.DataBaseType;

/**
 * 构建生成文件所需要的表的信息以及字段信息的数据
 * @author liqi
 *
 */
public final class MysqlStrategy extends AbstractDataBaseStrategy {

    /**mysql 查询所有的表*/
    public static final String SELECT_TABLE = "show table status ";
    /**mysql 查询表的字段明细*/
    public static final String SELECT_FIELD = "show full fields from %s ";

    private MysqlStrategy(Connection connection, DataBaseFieldEnum fieldEnum, List<String> tables,
            List<String> includePrefix) {
        super(connection, fieldEnum, tables, includePrefix);
    }

    /**
     * @param attr
     * @return
     */
    public static AbstractDataBaseStrategy getInstance(GeneratorAttr attr) {
        try {
            Connection conn = DriverManager.getConnection(attr.getUrl(), attr.getUser(), attr.getPassword());
            Class.forName(DataBaseDriver.MYSQL);
            return new MysqlStrategy(conn, DataBaseFieldEnum.MYSQL, attr.getTables(), attr.getIncludePrefix());
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    String getTableSql() {
        return SELECT_TABLE;
    }

    @Override
    String getFieldSql(String tableName) {
        return String.format(SELECT_FIELD, tableName);
    }

    @Override
    DataBaseType typeConvert(String fieldType) {
        return ConvertSingleFactory.getInstance().build(DataBaseDriver.MYSQL).processTypeConvert(fieldType);
    }

}
